import React, { useState, useEffect, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { 
  Card, 
  Tag, 
  Button, 
  Input, 
  Select, 
  Space, 
  Empty,
  Spin,
  Tabs,
  Row,
  Col,
  Alert,
  message,
  Pagination
} from 'antd';
import { 
  PlusOutlined, 
  SearchOutlined,
  ClockCircleOutlined,
  UserOutlined,
  GiftOutlined,
  MessageOutlined
} from '@ant-design/icons';
import type { Post } from '../../types';
import './Help.scss';

const { Search } = Input;
const { Option } = Select;

const Help: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [posts, setPosts] = useState<Post[]>([]);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [activeTab, setActiveTab] = useState('all');
  const [typeFilter, setTypeFilter] = useState<'all' | string>('all');
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(9); // 每页9个（3x3网格）

  // 模拟求助数据
  const mockPosts: Post[] = [
    {
      id: '1',
      title: '求推荐好用的学习软件',
      content: '最近在学习编程，有什么好的IDE推荐吗？最好是免费的，适合初学者的。需要支持Python和JavaScript。',
      author: { id: '1', username: '编程新手', avatar: '', email: 'newbie@example.com', role: 'student' },
      category: 'help',
      helpType: '学习求助',
      helpStatus: 'pending',
      tags: ['学习', '编程', 'IDE'],
      contact: 'QQ: 123456789',
      requirements: '免费、支持Python和JavaScript、适合新手',
      reward: '',
      createdAt: '2024-01-15T10:30:00Z',
      updatedAt: '2024-01-15T10:30:00Z',
      likes: 0,
      comments: 0,
      views: 89,
    },
    {
      id: '2',
      title: '宿舍网络问题求助',
      content: '宿舍的网络经常断线，重启路由器也没用，有没有同学遇到过类似问题？急需解决！',
      author: { id: '2', username: '网络小白', email: 'network@example.com', role: 'student' },
      category: 'help',
      helpType: '生活求助',
      helpStatus: 'in_progress',
      tags: ['生活', '网络', '宿舍'],
      contact: '微信: wlxb2024',
      requirements: '最好能上门看看',
      reward: '请吃饭',
      createdAt: '2024-01-15T09:15:00Z',
      updatedAt: '2024-01-15T09:15:00Z',
      likes: 0,
      comments: 0,
      views: 67,
    },
    {
      id: '3',
      title: 'React Hooks 使用问题',
      content: '在使用useEffect时遇到了无限循环的问题，不知道是什么原因，求大神指导。已经查了很多资料还是没解决。',
      author: { id: '3', username: '前端菜鸟', email: 'frontend@example.com', role: 'student' },
      category: 'help',
      helpType: '技术求助',
      helpStatus: 'resolved',
      tags: ['技术', 'React', 'Hooks'],
      contact: '邮箱: frontend@example.com',
      requirements: '能远程指导最好',
      reward: '红包 20元',
      createdAt: '2024-01-15T08:45:00Z',
      updatedAt: '2024-01-15T08:45:00Z',
      likes: 0,
      comments: 0,
      views: 123,
    },
    {
      id: '4',
      title: '如何提高学习效率？',
      content: '感觉学习效率很低，总是容易分心，有什么好的方法可以提高专注力吗？求学霸分享经验！',
      author: { id: '4', username: '学习困难户', email: 'study@example.com', role: 'student' },
      category: 'help',
      helpType: '学习求助',
      helpStatus: 'pending',
      tags: ['学习', '效率', '专注力'],
      contact: 'QQ: 987654321',
      requirements: '有实际经验的同学',
      reward: '无',
      createdAt: '2024-01-14T16:30:00Z',
      updatedAt: '2024-01-14T16:30:00Z',
      likes: 0,
      comments: 0,
      views: 156,
    },
    {
      id: '5',
      title: '宿舍室友太吵怎么办？',
      content: '室友经常在晚上打游戏到很晚，影响休息，沟通过但效果不好，有什么建议吗？真的很困扰。',
      author: { id: '5', username: '睡眠困难户', email: 'sleep@example.com', role: 'student' },
      category: 'help',
      helpType: '生活求助',
      helpStatus: 'in_progress',
      tags: ['生活', '室友', '睡眠'],
      contact: '站内私信',
      requirements: '有类似经历的同学',
      createdAt: '2024-01-14T14:20:00Z',
      updatedAt: '2024-01-14T14:20:00Z',
      likes: 0,
      comments: 0,
      views: 98,
    },
    {
      id: '6',
      title: '数据库设计问题求助',
      content: '在设计用户表时遇到了一些问题，不知道字段应该如何设计，求指导。有完整的需求文档。',
      author: { id: '6', username: '数据库新手', email: 'database@example.com', role: 'student' },
      category: 'help',
      helpType: '技术求助',
      helpStatus: 'pending',
      tags: ['技术', '数据库', '设计'],
      contact: '微信: db_newbie',
      requirements: '熟悉MySQL数据库',
      reward: '红包 50元',
      createdAt: '2024-01-14T11:15:00Z',
      updatedAt: '2024-01-14T11:15:00Z',
      likes: 0,
      comments: 0,
      views: 76,
    },
  ];

  const subCategories = [
    { key: 'all', label: '全部求助' },
    { key: 'study', label: '学习求助' },
    { key: 'life', label: '生活求助' },
    { key: 'tech', label: '技术求助' },
  ];

  useEffect(() => {
    loadPosts();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const loadPosts = async () => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      setPosts(mockPosts);
    } catch (error) {
      console.error('加载求助失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 过滤帖子
  const filteredPosts = useMemo(() => {
    const filtered = posts.filter(post => {
      // 按分类过滤
      if (activeTab !== 'all') {
        const typeMatch = {
          study: '学习求助',
          life: '生活求助',
          tech: '技术求助',
        }[activeTab];
        if (post.helpType !== typeMatch) return false;
      }

      // 按类型筛选
      if (typeFilter !== 'all' && post.helpType !== typeFilter) {
        return false;
      }

      // 按关键词搜索
      if (searchKeyword) {
        return (
          post.title.includes(searchKeyword) ||
          post.content.includes(searchKeyword) ||
          post.tags.some(tag => tag.includes(searchKeyword))
        );
      }

      return true;
    });
    
    // 分页
    const start = (currentPage - 1) * pageSize;
    const end = start + pageSize;
    return filtered.slice(start, end);
  }, [posts, activeTab, typeFilter, searchKeyword, currentPage, pageSize]);
  
  // 总数
  const totalPosts = useMemo(() => {
    return posts.filter(post => {
      if (activeTab !== 'all') {
        const typeMatch = {
          study: '学习求助',
          life: '生活求助',
          tech: '技术求助',
        }[activeTab];
        if (post.helpType !== typeMatch) return false;
      }
      if (typeFilter !== 'all' && post.helpType !== typeFilter) {
        return false;
      }
      if (searchKeyword) {
        return (
          post.title.includes(searchKeyword) ||
          post.content.includes(searchKeyword) ||
          post.tags.some(tag => tag.includes(searchKeyword))
        );
      }
      return true;
    }).length;
  }, [posts, activeTab, typeFilter, searchKeyword]);

  const handleContact = (post: Post, e: React.MouseEvent) => {
    e.stopPropagation();
    // TODO: 打开站内对话
    console.log('联系求助者:', post.author.username);
    message.info('站内对话功能开发中...');
  };

  const handleSearch = (value: string) => {
    setSearchKeyword(value);
    setCurrentPage(1);
  };

  const handleTabChange = (key: string) => {
    setActiveTab(key);
    setCurrentPage(1);
  };
  
  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    
    if (days === 0) {
      return '今天';
    } else if (days === 1) {
      return '昨天';
    } else if (days < 7) {
      return `${days}天前`;
    } else {
      return date.toLocaleDateString();
    }
  };

  const getTypeColor = (type: string) => {
    const colors = {
      '学习求助': 'blue',
      '生活求助': 'green',
      '技术求助': 'orange',
    };
    return colors[type as keyof typeof colors] || 'default';
  };

  return (
    <div className="help-page">
      <div className="page-header">
        <div className="header-left">
          <h1>求助区</h1>
          <p>互帮互助，共同进步，校园温暖</p>
        </div>
      </div>

      {/* 求助须知 */}
      <Alert
        message="求助须知"
        description="发布求助时请详细描述问题，填写联系方式方便其他同学联系你。问题解决后请及时更新状态。"
        type="info"
        showIcon
        style={{ marginBottom: 16 }}
      />

      {/* 子分类标签 */}
      <Card className="category-card">
        <Tabs 
          activeKey={activeTab} 
          onChange={handleTabChange}
          items={subCategories.map(cat => ({
            key: cat.key,
            label: cat.label,
          }))}
        />
      </Card>

      {/* 筛选和搜索 */}
      <Card className="filter-card">
        <div className="filter-content">
          <Space size="middle" wrap>
            <Search
              placeholder="搜索求助内容..."
              allowClear
              onSearch={handleSearch}
              style={{ width: 300 }}
              prefix={<SearchOutlined />}
            />
            <Select
              value={typeFilter}
              onChange={setTypeFilter}
              style={{ width: 140 }}
            >
              <Option value="all">全部类型</Option>
              <Option value="学习求助">学习求助</Option>
              <Option value="生活求助">生活求助</Option>
              <Option value="技术求助">技术求助</Option>
            </Select>
          </Space>
        </div>
      </Card>

      {/* 求助卡片列表 */}
      <Card className="posts-card">
        <Spin spinning={loading}>
          {filteredPosts.length > 0 ? (
            <Row gutter={[16, 16]}>
              {filteredPosts.map((post) => {
                return (
                  <Col xs={24} sm={12} lg={8} key={post.id}>
                    <Card
                      hoverable
                      className="help-card"
                    >
                      <div className="help-type-badge">
                        <Tag color={getTypeColor(post.helpType || '')} style={{ fontSize: 13, padding: '2px 10px' }}>
                          {post.helpType}
                        </Tag>
                      </div>

                      <h3 className="help-title" title={post.title}>
                        {post.title}
                      </h3>

                      <p className="help-content">
                        {post.content}
                      </p>

                      <div className="help-info">
                        <div className="help-info-item">
                          <UserOutlined />
                          <span>{post.author.username}</span>
                        </div>
                        <div className="help-info-item">
                          <ClockCircleOutlined />
                          <span>{formatDate(post.createdAt)}</span>
                        </div>
                        <div className="help-info-item reward">
                          <GiftOutlined />
                          <span>{post.reward}</span>
                        </div>
                      </div>

                      <div className="help-footer">
                        <Button 
                          type="primary" 
                          icon={<MessageOutlined />}
                          block
                          onClick={(e) => handleContact(post, e)}
                        >
                          联系TA
                        </Button>
                      </div>
                    </Card>
                  </Col>
                );
              })}
            </Row>
          ) : (
            <Empty 
              description="暂无求助内容"
              image={Empty.PRESENTED_IMAGE_SIMPLE}
            />
          )}
        </Spin>
        
        {totalPosts > 0 && (
          <div className="pagination-wrapper">
            <Pagination
              current={currentPage}
              total={totalPosts}
              pageSize={pageSize}
              onChange={handlePageChange}
              showSizeChanger={false}
              showTotal={(total, range) => 
                `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
              }
            />
          </div>
        )}
      </Card>
    </div>
  );
};

export default Help;
